<template>
	<view class="inventory-page">
		<!-- 页面标题 -->
		<view class="page-title">出库单</view>
		<view class="form_head">
			<view class="info_item">
				<view>选择仓库:</view>
				<picker mode="selector" :range="warehouseOption" range-key="label" @change="seleWareHouse">
					<view style="font-weight: 500; display: flex">
						<view class="">{{ warehouse.label || '请选择仓库' }}</view>
						<view><uni-icons type="down" size="20" color="#55aaff"></uni-icons></view>
					</view>
				</picker>
			</view>
			<view class="info_item">货主信息:{{ mainBody.id + '--' + mainBody.name || '尚无名称' }}</view>
			<view class="form_code">
				<text>出库单号：{{ getFormId('OUT') }}</text>
			</view>
		</view>

		<!-- 搜索栏 -->
		<view class="search-bar">
			<input v-model="searchKey" placeholder="搜索商品名称/条码/批次号/一物一码" @input="handleSearchInput" class="search-input" />
		</view>

		<!-- 筛选面板 -->
		<view class="filter-panel">
			<view class="collapse">
				<view class="collapse-header" @click="toggleCollapse">
					<text>高级筛选</text>
					<view class="arrow" :class="{ rotate: isCollapsed }">
						{{ isCollapsed ? '↑' : '↓' }}
					</view>
				</view>
				<view class="collapse-content" v-if="isCollapsed">
					<view class="filter-group">
						<!-- 产品状态筛选 -->
						<view class="filter-item">
							<text class="filter-label">产品状态：</text>
							<view class="select-wrapper">
								<select v-model="filterParams.checkType" class="select-control">
									<option value="">全部状态</option>
									<option value="normal">正常</option>
									<option value="invalidDate">无效日期</option>
									<option value="breakage">破损沾污</option>
									<option value="invalidBatch">无效批次</option>
									<option value="invalidEncoding">无效编码</option>
								</select>
							</view>
						</view>

						<!-- 生产日期筛选 -->
						<view class="filter-item">
							<text class="filter-label">生产日期：</text>
							<input type="date" v-model="filterParams.productionDateStart" class="date-input" placeholder="开始日期" />
							<text class="range-separator">至</text>
							<input type="date" v-model="filterParams.productionDateEnd" class="date-input" placeholder="结束日期" />
						</view>

						<!-- 一物一码筛选 -->
						<view class="filter-item">
							<input v-model="filterParams.productionCode" placeholder="输入一物一码" class="text-input" />
						</view>

						<!-- 批次号筛选 -->
						<view class="filter-item">
							<input v-model="filterParams.batchNo" placeholder="输入批次号" class="text-input" />
						</view>

						<!-- 筛选操作按钮 -->
						<view class="filter-actions">
							<button @click="resetFilter" class="btn reset-btn">重置</button>
							<button @click="applyFilter" class="btn primary-btn">应用筛选</button>
						</view>

						<!-- 筛选结果统计 -->
						<view class="filter-stats" v-if="isFilterApplied">
							<text>筛选结果：共 {{ filteredCount }} 条数据，涉及 {{ productCount }} 个产品</text>
						</view>
					</view>
				</view>
			</view>
		</view>
		<!-- 操作按钮区 -->
		<view class="operation-buttons">
			<button @click="exportFilteredData" class="btn primary-btn plain">
				<text class="icon">↓</text>
				导出数据
			</button>
			<button @click="refreshData" class="btn default-btn">
				<text class="icon">↺</text>
				刷新数据
			</button>
		</view>
		<!-- 库存列表内容区 -->
		<view class="inventory-content">
			<!-- 加载中状态 -->
			<view v-if="isLoading" class="loading-state">
				<view class="spinner"></view>
				<text>加载中...</text>
			</view>
			<!-- 空状态 -->
			<view class="empty-state" v-if="!isLoading && filteredCount === 0">
				<view class="empty-icon">∅</view>
				<text>暂无符合条件的库存数据</text>
			</view>
			<!-- 产品合计视图 -->
			<view v-if="!isLoading && filteredCount > 0">
				<view class="product-total">
					<uni-table>
						<uni-th width="10">行</uni-th>
						<uni-th  width="50">图片</uni-th>
						<uni-th   width="150" :sortable='true'>商品名称</uni-th>
						<uni-th  width="200">规格</uni-th>
						<uni-th  width="200">条码</uni-th>
						<uni-th width="150">总库存数</uni-th>
						<uni-th width="150">出库数量</uni-th>
                        <template v-for="(productGroup, productId, index) in filteredInventory"
							:key="productId">
						<uni-tr
						
							
							@click="selecProduct(productId, index)"
							:class="{ selcet_tr: index === selecIndex }"
						>
						
							<uni-td>{{ index + 1 }}</uni-td>
							<uni-td>
								<view class="product_img" @click="preViewimg(productGroup.photos)">
									<image :src="productGroup.photos[0]" mode="aspectFit"></image>
								</view>
							</uni-td>
							<uni-td>{{ productGroup.productName }}</uni-td>
							<uni-td>{{ productGroup.spec ? productGroup.spec.specStr : '无规格' }}</uni-td>
							<uni-td>{{ productGroup.barcodes }}</uni-td>
							<uni-td>{{ unitRead(productId, productGroup.totalQuantity) }}</uni-td>
							<uni-td>{{ '出库数' }}</uni-td>
							
						</uni-tr>
						<uni-tr v-if="index === selecIndex" >
							<uni-td colspan="30" align="right">
								<view >
									<!-- 显示产品状态模式 -->
									<view class="display-mode">
										<view class="segmented-control">
											<view
												v-for="(mode, index) in ['产品合计', '批次明细', '一物一码明细', '生产日期']"
												:key="index"
												@click="handleDisplayModeChange(index, productId)"
												:class="{ 'segmented-item': true, active: displayMode === index }"
											>
												<view class="">
													<label class="radio">
														<radio value="" foreColor="#fff" active-background-color="#55aaff" :checked="displayMode === index" disabled="true" />
														<text>{{ mode }}</text>
													</label>
												</view>
											</view>
										</view>
									</view>
									<!-- 产品状态模式 -->
									<view class="" v-if="renderType === 'productTotal'">
										<uni-table>
											<uni-tr>
												<uni-th width="200">产品编码</uni-th>
												<uni-th width="200" :sortable='true'>库存数量</uni-th>
												<uni-th width="200">出库数量</uni-th>
												<uni-th width="200">单位</uni-th>
												<uni-th>总出库数</uni-th>
											</uni-tr>
											<uni-tr v-for="(value, key, index) in selecProductResult" :key="index">
												<uni-td>
													<view class="" :style="{ color: typeMap(key).statusColors }">{{ typeMap(key).title }}</view>
												</uni-td>
												<uni-td>{{ unitRead(productId, value.totalQuantity) }}</uni-td>
												<uni-td>
													<input type="number" v-model="value.unitQuantity" placeholder="输入数量" />
												</uni-td>
												<uni-td>
													<picker mode="selector" :range="units(productId)" range-key="unitName" @change="seleUnit($event, 'productionCode', key, productId)">
														{{ value.selectUnit.unitName || '选择单位' }}
													</picker>
												</uni-td>
												<uni-td>
													{{ unitRead(productId, value.outQuantity) || '无' }}
												</uni-td>
												<uni-td>
													<view class="out_btn" @click="outSure('checkType', key, productId, value.unitQuantity)">
														<uni-icons type="checkmarkempty" size="20"></uni-icons>
													</view>
												</uni-td>
											</uni-tr>
										</uni-table>
									</view>
								</view>
								<!-- 显示产品批次模式 -->
								<view v-if="!isLoading && index === selecIndex">
									<view class="" v-if="renderType === 'batchDetail' && filteredCount > 0">
										<uni-table>
											<uni-tr>
												<uni-th width="200">生产批次</uni-th>
												<uni-th width="200" :sortable='true'>库存数量</uni-th>
												<uni-th width="200">出库数量</uni-th>
												<uni-th width="200">单位</uni-th>
												<uni-th>总出库数</uni-th>
											</uni-tr>
											<uni-tr v-for="(value, key, index) in selecProductResult" :key="index">
												<uni-td>{{ key || '无批次号' }}</uni-td>
												<uni-td>{{ unitRead(productId, value.totalQuantity) }}</uni-td>
												<uni-td>
													<input type="number" v-model="value.unitQuantity" placeholder="输入数量" />
												</uni-td>
												<uni-td>
													<picker mode="selector" :range="units(productId)" range-key="unitName" @change="seleUnit($event, 'productionCode', key, productId)">
														{{ value.selectUnit.unitName || '选择单位' }}
													</picker>
												</uni-td>
												<uni-td>
													{{ unitRead(productId, value.outQuantity) || '无' }}
												</uni-td>
												<uni-td>
													<view class="out_btn" @click="outSure('batchNo', key, productId, value.unitQuantity)">
														<uni-icons type="checkmarkempty" size="20"></uni-icons>
													</view>
												</uni-td>
											</uni-tr>
										</uni-table>
									</view>
								</view>
								<!-- 生产日期模式 -->
								<view v-if="!isLoading && index === selecIndex">
									<view class="" v-if="renderType === 'productionDate' && filteredCount > 0">
										<uni-table :stripe="true">
											<uni-tr>
												<uni-th width="200" :sortable='true'>生产日期</uni-th>
												<uni-th width="200" :sortable='true'>库存数量</uni-th>
												<uni-th width="200" :sortable='true'>出库数量</uni-th>
												<uni-th>单位</uni-th>
												<uni-th>总出库数</uni-th>
											</uni-tr>
											<uni-tr v-for="(value, key, index) in selecProductResult" :key="index">
												<uni-td>{{ key || '无生产日期' }}</uni-td>
												<uni-td>{{ unitRead(productId, value.totalQuantity) }}</uni-td>
												<uni-td>
													<input type="number" v-model="value.unitQuantity" placeholder="输入数量" />
												</uni-td>
												<uni-td>
													<picker mode="selector" :range="units(productId)" range-key="unitName" @change="seleUnit($event, 'productionCode', key, productId)">
														{{ value.selectUnit.unitName || '选择单位' }}
													</picker>
												</uni-td>
												<uni-td>
													{{ unitRead(productId, value.outQuantity) || '无' }}
												</uni-td>
												<uni-td>
													<view class="out_btn" @click="outSure('productionDate', key, productId, value.unitQuantity)">
														<uni-icons type="checkmarkempty" size="20"></uni-icons>
													</view>
												</uni-td>
											</uni-tr>
										</uni-table>
									</view>
								</view>
								<!-- 产品编码模式 -->
								<view v-if="!isLoading && index === selecIndex">
									<view class="" v-if="renderType === 'productionCode' && filteredCount > 0">
										<uni-table>
											<uni-tr>
												<uni-th width="200">产品编码</uni-th>
												<uni-th width="200" :sortable='true'>库存数量</uni-th>
												<uni-th width="200">出库数量</uni-th>
												<uni-th width="200">单位</uni-th>
												<uni-th>总出库数</uni-th>
											</uni-tr>
											<uni-tr v-for="(value, key, index) in selecProductResult" :key="index">
												<uni-td>{{ key || '无产品编码' }}</uni-td>
												<uni-td>{{ unitRead(productId, value.totalQuantity) }}</uni-td>
												<uni-td>
													<view class="quantity">
														<input type="number" v-model="value.unitQuantity" placeholder="输入数量" />
													</view>
												</uni-td>
												<uni-td>
													<view class="unit">
														<picker mode="selector" :range="units(productId)" range-key="unitName" @change="seleUnit($event, 'productionCode', key, productId)">
															<view class="unit_item">{{ value.selectUnit.unitName || '选择单位' }}</view>
														</picker>
													</view>
												</uni-td>
												<uni-td>
													<view class="note">
														<view class="">{{ unitRead(productId, value.outQuantity) || '无' }}</view>
													</view>
												</uni-td>
												<uni-td>
													<view class="out_btn" @click="outSure('productionCode', key, productId, value.unitQuantity)">
														<uni-icons type="checkmarkempty" size="20"></uni-icons>
													</view>
												</uni-td>
											</uni-tr>
										</uni-table>
									</view>
								</view>
								
							</uni-td>
						</uni-tr>
						</template>
					</uni-table>
				
				</view>
			</view>
		</view>
		<!-- 加载更多 -->
		<view v-if="hasMoreData && !isLoading" @click="loadMoreData" class="load-more">
			<text>{{ loadMoreStatus === 'loading' ? '加载中...' : '点击加载更多' }}</text>
		</view>
	</view>
</template>
<script>
const cloudDB = uniCloud.importObject('getDb');
import { acceptType } from '../untils/acceptType.js';
import unitRead from '../untils/unitRead';
import { formatDate } from '../untils/formatDate.js';
import { userMainStore } from '@/store/mainStore.js';
const mainStore = userMainStore();
import getFormId from '../untils/getFormId.js';

export default {
	data() {
		return {
			outForm: {
				productId: '',
				unit: { id: '', unitName: '' },
				outQuantity: 0,
				appForQuantity: 0
			},
			outList: [],
			outQuantity: 0,

			warehouse: {},
			mainBody: {},
			rawInventory: [],
			filteredInventoryList: [],
			isLoading: false,
			loadMoreStatus: 'more',
			hasMoreData: true,
			pageSize: 20,
			acceptType,
			currentPage: 1,
			selecIndex: -1,
			selecProductResult: null,
			// 搜索与筛选
			searchKey: '',
			filterParams: {
				checkType: '',
				productionDateStart: '',
				productionDateEnd: '',
				productionCode: '',
				batchNo: ''
			},
			isFilterApplied: false,

			// 显示模式
			displayMode: 0,
			renderType: 'productTotal',

			// 折叠面板状态
			isCollapsed: false,
			warehouseOption: [],
			supplierOption: [],

			// 搜索防抖计时器
			searchTimer: null
		};
	},

	computed: {
		// 筛选后的库存分组数据
		filteredInventory() {
			return this.groupByProductId(this.filteredInventoryList);
		},

		// 筛选结果统计
		filteredCount() {
			return this.filteredInventoryList.length;
		},

		// 产品数量统计
		productCount() {
			return Object.keys(this.filteredInventory).length;
		}
	},

	mounted() {
		this.getMainBody();
		this.mainBody = mainStore.mainObject;
		this.loadFilterState();
		this.loadInventoryData();
	},

	methods: {
		// 切换折叠面板
		getFormId,
		toggleCollapse() {
			this.isCollapsed = !this.isCollapsed;
		},
		async getMainBody() {
			try {
				const r = await cloudDB.getDB('supplier', { code: mainStore.mainObject.id });

				if (r.code) {
					const warehouses = r.data[0]?.warehouse || []; // 增加可选链和默认空数组

					this.warehouseOption = warehouses.map((item) => ({
						...item,
						label: `${item.code}---${item.warehouse_name ?? '无名仓库'}`
					}));
					console.log(JSON.stringify(this.warehouseOption));
				}
			} catch (error) {
				console.error('获取数据失败', error);
				// 可以添加错误处理逻辑，如提示用户
			}
		},
		seleWareHouse(e) {
			this.warehouse = this.warehouseOption[e.detail.value];
		},
		// 加载库存数据
		async loadInventoryData(refresh = false) {
			if (refresh) {
				this.currentPage = 1;
				this.hasMoreData = true;
			}

			this.isLoading = true;
			try {
				const res = await cloudDB.getInentory({});
				console.log('库存数据', res.data);
				if (refresh) {
					this.rawInventory = res.data.map((item) => ({
						...item,
						outQuantity: 0,
						appForQuantity: 0,
						selectUnit: {},
						unitQuantity: 0
					}));
				} else {
					this.rawInventory = [...this.rawInventory, ...res.data].map((item) => ({
						...item,
						outQuantity: 0,
						appForQuantity: 0,
						selectUnit: {},
						unitQuantity: 0
					}));
				}

				// 检查是否有更多数据
				if (res.data.length < this.pageSize) {
					this.hasMoreData = false;
					this.loadMoreStatus = 'noMore';
				}

				// 应用筛选和搜索
				this.applyFiltersAndSearch();
			} catch (err) {
				console.error('加载库存数据失败：', err);
				uni.showToast({ title: '加载失败', icon: 'none' });
			} finally {
				this.isLoading = false;
				this.loadMoreStatus = 'more';
			}
		},
		unitRead(productId, quantity) {
			const index = productId.indexOf('{');
			const id = index !== -1 ? productId.slice(0, index) : productId;
			const selectProduct = this.filteredInventoryList.find((item) => item.productId && item.productId.some((product) => product._id === id));
			const units = selectProduct.productId[0].unit;

			return unitRead(units, units[0].id, quantity);
		},
		units(productId) {
			const index = productId.indexOf('{');
			const id = index !== -1 ? productId.slice(0, index) : productId;
			const selectProduct = this.filteredInventoryList.find((item) => item.productId && item.productId.some((product) => product._id === id));
			const units = selectProduct.productId[0].unit;

			return units;
		},

		// 加载更多数据
		loadMoreData() {
			if (this.isLoading || !this.hasMoreData) return;

			this.currentPage++;
			this.loadMoreStatus = 'loading';
			this.loadInventoryData();
		},
		typeMap(key) {
			const type = this.acceptType.find((item) => item.type === key);
			return type;
		},
		// 刷新数据
		refreshData() {
			this.loadInventoryData(true);
			uni.showToast({ title: '已刷新', icon: 'none' });
		},
		jsonParse(spec) {
			const obj = JSON.parse(spec);
			if (Object.keys(obj).length > 0) {
				return obj;
			} else return null;
		},
		// 处理搜索输入
		handleSearchInput() {
			// 搜索防抖处理
			clearTimeout(this.searchTimer);
			this.searchTimer = setTimeout(() => {
				this.applyFiltersAndSearch();
			}, 300);
		},
		selecProduct(productId, index) {
			// 切换选中状态
			this.selecProductResult = null;
			if (this.selecIndex === index) {
				this.selecIndex = -1;
			} else {
				this.selecIndex = index;
			}

			this.handleDisplayModeChange(this.displayMode, productId);
			// 提取id（大括号前面的内容）
		},

		reduceCheckType(selectProducts) {
			this.selecProductResult = null;
			const result = selectProducts.reduce((acc, item) => {
				// 修复：获取checkType中的type属性（原代码直接使用了checkType本身）
				const type = item.checkType || 'unknown';

				// 修复：正确初始化对象（原代码在属性不存在时直接赋值会报错）
				if (!acc[type]) {
					acc[type] = {
						totalQuantity: 0,
						count: 0,
						outQuantity: 0,
						appForQuantity: 0
					};
				}

				// 累加数量
				const quantity = typeof item.currentQuantity === 'number' ? item.currentQuantity : 0;
				const outQuantity = typeof item.outQuantity === 'number' ? item.outQuantity : 0;
				const appForQuantity = typeof item.appForQuantity === 'number' ? item.appForQuantity : 0;
				acc[type].totalQuantity += quantity;
				acc[type].outQuantity += outQuantity;
				acc[type].appForQuantity += appForQuantity;
				acc[type].count += 1;
				acc[type].selectUnit = item.selectUnit;
				acc[type].unitQuantity = item.unitQuantity;

				return acc;
			}, {}); // 初始值为空对象

			this.selecProductResult = result;
	
		},
		reduceBatch(selectProducts) {
			const result = selectProducts.reduce((acc, item) => {
				// 修复：获取checkType中的type属性（原代码直接使用了checkType本身）
				const type = item.batchNo ;

				// 修复：正确初始化对象（原代码在属性不存在时直接赋值会报错）
				if (!acc[type]) {
					acc[type] = {
						totalQuantity: 0,
						count: 0,
						outQuantity: 0,
						unitQuantity: 0,
						appForQuantity: 0
					};
				}

				// 累加数量
				const quantity = typeof item.currentQuantity === 'number' ? item.currentQuantity : 0;
				const outQuantity = typeof item.outQuantity === 'number' ? item.outQuantity : 0;
				const appForQuantity = typeof item.appForQuantity === 'number' ? item.appForQuantity : 0;
				acc[type].totalQuantity += quantity;
				acc[type].outQuantity += outQuantity;
				acc[type].appForQuantity += appForQuantity;
				acc[type].count += 1;
				acc[type].selectUnit = item.selectUnit;
				acc[type].unitQuantity = item.unitQuantity;
				return acc;
			}, {}); // 初始值为空对象

			this.selecProductResult = result;
			console.log('...666', JSON.stringify(this.selecProductResult));
		},
		reduceProductionDate(selectProducts) {
			const result = selectProducts.reduce((acc, item) => {
				// 修复：获取checkType中的type属性（原代码直接使用了checkType本身）
				const type = item.productionDate ;

				// 修复：正确初始化对象（原代码在属性不存在时直接赋值会报错）
				if (!acc[type]) {
					acc[type] = {
						totalQuantity: 0,
						count: 0,
						outQuantity: 0,
						appForQuantity: 0
					};
				}

				// 累加数量
				const quantity = typeof item.currentQuantity === 'number' ? item.currentQuantity : 0;
				const outQuantity = typeof item.outQuantity === 'number' ? item.outQuantity : 0;
				const appForQuantity = typeof item.appForQuantity === 'number' ? item.appForQuantity : 0;
				acc[type].totalQuantity += quantity;
				acc[type].outQuantity += outQuantity;
				acc[type].appForQuantity += appForQuantity;
				acc[type].count += 1;
				acc[type].selectUnit = item.selectUnit;
				acc[type].unitQuantity = item.unitQuantity;

				return acc;
			}, {}); // 初始值为空对象

			this.selecProductResult = result;
		},
		reduceProductionCode(selectProducts) {
			const result = selectProducts.reduce((acc, item) => {
				// 修复：获取checkType中的type属性（原代码直接使用了checkType本身）
				const type = item.productionCode ;

				// 修复：正确初始化对象（原代码在属性不存在时直接赋值会报错）
				if (!acc[type]) {
					acc[type] = {
						totalQuantity: 0,
						count: 0,
						outQuantity: 0,
						appForQuantity: 0
					};
				}

				// 累加数量
				const quantity = typeof item.currentQuantity === 'number' ? item.currentQuantity : 0;
				const outQuantity = typeof item.outQuantity === 'number' ? item.outQuantity : 0;
				const appForQuantity = typeof item.appForQuantity === 'number' ? item.appForQuantity : 0;
				acc[type].totalQuantity += quantity;
				acc[type].outQuantity += outQuantity;
				acc[type].appForQuantity += appForQuantity;
				acc[type].count += 1;
				acc[type].selectUnit = item.selectUnit;
				acc[type].unitQuantity = item.unitQuantity;

				return acc;
			}, {}); // 初始值为空对象

			this.selecProductResult = result;
		},

		// 应用筛选和搜索
		applyFiltersAndSearch() {
			let filtered = [...this.rawInventory];

			// 应用搜索
			if (this.searchKey) {
				const searchStr = this.searchKey.toLowerCase();
				filtered = filtered.filter((item) => {
					// 搜索商品名称
					const productNames = this.getProductName(item.productId);
					// 搜索产品ID
					const productId = this.getProductId(item.productId).toLowerCase();
					// 搜索批次号
					const batchNo = (item.batchNo || '').toLowerCase();
					// 搜索一物一码
					const productionCode = (item.productionCode || '').toLowerCase();
					const barcodes = this.getProductBarcode(item.productId);
					return (
						productNames.some((item) => item.goodName.toLowerCase().includes(searchStr)) ||
						barcodes.some((item) => item.includes(searchStr)) ||
						productId.includes(searchStr) ||
						batchNo.includes(searchStr) ||
						productionCode.includes(searchStr)
					);
				});
			}

			// 应用筛选条件
			if (this.filterParams.checkType) {
				filtered = filtered.filter((item) => item.checkType === this.filterParams.checkType);
			}

			if (this.filterParams.productionDateStart) {
				filtered = filtered.filter((item) => {
					return new Date(item.productionDate) >= new Date(this.filterParams.productionDateStart);
				});
			}

			if (this.filterParams.productionDateEnd) {
				filtered = filtered.filter((item) => {
					return new Date(item.productionDate) <= new Date(this.filterParams.productionDateEnd);
				});
			}

			if (this.filterParams.productionCode) {
				filtered = filtered.filter((item) => item.productionCode === this.filterParams.productionCode);
			}

			if (this.filterParams.batchNo) {
				filtered = filtered.filter(
					(item) => item.batchNo === this.filterParams.batchNo || (item.batchQuantity && item.batchQuantity.some((batch) => batch.batchNo === this.filterParams.batchNo))
				);
			}

			this.filteredInventoryList = filtered;
		},

		// 处理显示模式切换
		handleDisplayModeChange(index, productId) {
			this.displayMode = index;
			console.log(this.displayMode);
			this.selecProductResult = null;
			// 设置渲染类型
			switch (index) {
				case 0:
					this.renderType = 'productTotal';
					break;
				case 1:
					this.renderType = 'batchDetail';
					break;
				case 2:
					this.renderType = 'productionCode';
					break;
				case 3:
					this.renderType = 'productionDate';
					break;
			}
			const idx = productId.indexOf('{');
			const id = idx !== -1 ? productId.slice(0, idx) : productId;

			// 提取spec（包含大括号的部分）
			let spec = '';
			const startIndex = productId.indexOf('{');
			const endIndex = productId.indexOf('}');
			if (startIndex !== -1 && endIndex !== -1 && endIndex > startIndex) {
				spec = productId.slice(startIndex, endIndex + 1);
			}

			// 筛选同时满足两个条件的产品：
			// 1. productId数组中包含_id等于id的项
			// 2. item.spec等于提取的spec
			const selectProducts = this.filteredInventoryList.filter((item) => {
				// 检查productId条件
				const hasMatchingProductId = Array.isArray(item.productId) && item.productId.some((someItem) => someItem._id === id);

				// 检查spec条件（如果spec存在才验证，不存在则只验证productId）
				const hasMatchingSpec = spec ? item.spec === spec : true;

				// 两个条件都满足才保留
				return hasMatchingProductId && hasMatchingSpec;
			});

			console.log('筛选结果:', selectProducts);

			// 根据渲染类型执行对应处理
			if (this.renderType === 'productTotal') {
				this.reduceCheckType(selectProducts);
			} else if (this.renderType === 'batchDetail') {
				this.reduceBatch(selectProducts);
			} else if (this.renderType === 'productionDate') {
				this.reduceProductionDate(selectProducts);
			} else {
				this.reduceProductionCode(selectProducts);
			}
		},

		// 应用筛选
		applyFilter() {
			this.isFilterApplied = true;
			uni.setStorageSync('inventoryFilterParams', this.filterParams);
			this.loadInventoryData(true); // 重新加载数据
		},

		// 重置筛选
		resetFilter() {
			this.filterParams = {
				checkType: '',
				productionDateStart: '',
				productionDateEnd: '',
				productionCode: '',
				batchNo: ''
			};
			this.isFilterApplied = false;
			uni.removeStorageSync('inventoryFilterParams');
			this.loadInventoryData(true); // 重新加载数据
		},

		// 加载筛选状态
		loadFilterState() {
			const savedFilter = uni.getStorageSync('inventoryFilterParams');
			if (savedFilter) {
				this.filterParams = savedFilter;
				this.isFilterApplied = true;
			}
		},

		// 按产品ID分组聚合（适配联表后的数据结构）
		groupByProductId(inventoryList) {
			return inventoryList.reduce((groups, item) => {
				// 获取实际产品ID（联表后为数组结构）

				const productId = this.getProductId(item.productId);
				const specStr = item.spec;
				if (!groups[`${productId}${specStr}`]) {
					groups[`${productId}${specStr}`] = {
						totalQuantity: 0,
						batchList: [],
						productName: this.getProductName(item.productId)[0].goodName, // 存储商品名称
						spec: this.jsonParse(item.spec)
					};
				}

				// 累加总库存
				groups[`${productId}${specStr}`].totalQuantity += item.currentQuantity;
				groups[`${productId}${specStr}`].photos = this.getProductPhoto(item.productId);
				groups[`${productId}${specStr}`].barcodes = this.getProductBarcode(item.productId).join(',');

				// 处理批次数据
				if (item.batchNo) {
					// 检查批次是否已存在
					const existingBatch = groups[`${productId}${specStr}`].batchList.find((b) => b.batchNo === item.batchNo);
					if (existingBatch) {
						existingBatch.quantity += item.currentQuantity;
					} else {
						groups[`${productId}${specStr}`].batchList.push({
							batchNo: item.batchNo,
							quantity: item.currentQuantity
						});
					}
				} else if (item.batchQuantity && item.batchQuantity.length > 0) {
					item.batchQuantity.forEach((batch) => {
						const existingBatch = groups[`${productId}${specStr}`].batchList.find((b) => b.batchNo === batch.batchNo);
						if (existingBatch) {
							existingBatch.quantity += batch.quantity;
						} else {
							groups[`${productId}${specStr}`].batchList.push({ ...batch });
						}
					});
				}

				return groups;
			}, {});
		},

		// 导出筛选数据
		// 前端调用云对象方法
		async exportFilteredData() {
			if (this.filteredCount === 0) {
				uni.showToast({ title: '没有可导出的数据', icon: 'none' });
				return;
			}

			uni.showLoading({ title: '正在导出...' });
			try {
				// 实例化云对象

				// 调用导出方法
				const res = await cloudDB.exportInventoryData({
					exportData: this.filteredInventoryList,
					filterParams: this.filterParams,
					renderType: this.renderType
				});

				uni.hideLoading();
				// 下载并打开文件
				uni.downloadFile({
					url: res.downloadUrl,
					success: (downloadRes) => {
						uni.openDocument({
							filePath: downloadRes.tempFilePath,
							showMenu: true
						});
					}
				});
			} catch (err) {
				uni.hideLoading();
				console.error('导出失败：', err);
				uni.showToast({ title: '导出失败', icon: 'none' });
			}
		},

		// 格式化导出数据
		formatExportData(data) {
			return data.map((item) => ({
				商品名称: this.getProductName(item.productId),
				产品ID: this.getProductId(item.productId),
				产品状态: this.getCheckTypeText(item.checkType.title),
				批次号: item.batchNo || '无',
				一物一码: item.productionCode || '无',
				生产日期: this.formatDate(item.productionDate),
				库存数量: item.currentQuantity,
				最后更新时间: this.formatDate(item.lastUpdated)
			}));
		},

		// 获取产品状态文本
		getCheckTypeText(type) {
			const map = {
				normal: '正常',
				invalidDate: '无效日期',
				breakage: '破损沾污',
				invalidBatch: '无效批次',
				invalidEncoding: '无效编码'
			};
			return map[type] || '未知';
		},

		// 格式化日期
		formatDate,

		// 从联表数据中获取商品名称
		getProductName(productIdArr) {
			try {
				// 适配productId为数组结构：[{"_id":"...", "goodName":[{"goodName":"商品名"}]}]
				return productIdArr[0].goodName || [];
			} catch (err) {
				return '未知商品';
			}
		},

		// 从联表数据中获取产品ID
		getProductId(productIdArr) {
			try {
				// 提取实际产品ID
				return productIdArr[0]._id || '未知ID';
			} catch (err) {
				return '未知ID';
			}
		},
		getProductBarcode(productIdArr) {
			try {
				return productIdArr[0].barcode || [];
			} catch (err) {
				return '未知条码';
			}
		},
		getProductPhoto(productIdArr) {
			if (productIdArr[0].photo?.length > 0) {
				return productIdArr[0].photo.map((item) => item.url);
			}
		},
		preViewimg(imgs) {
			console.log(imgs);
			uni.previewImage({
				urls: imgs,
				indicator: 'number',
				loop: true
			});
		},
		/**
		 * @param {Object} e 选择商品单位的索引
		 * @param {Object} type 查询商品验收类型
		 * @param {Object} key 类型名称的值
		 * @param {Object} productId 商品的id加规格
		 */
		seleUnit(e, type, key, productId) {
			this.selecProductResult[key].selectUnit = this.units(productId)[e.detail.value];
		},
		outSure(type, key, productId, unitQuantity) {
			console.log('入参检查', type, key, productId, unitQuantity);
			if (unitQuantity === 0) {
				uni.showToast({
					icon: 'error',
					title: '请输入数量'
				});
				return;
			}
			if (Object.keys(this.selecProductResult[key].selectUnit).length === 0) {
				uni.showToast({
					icon: 'error',
					title: '请选择单位'
				});
				return;
			}
			this.selecProductResult[key].appForQuantity = unitQuantity * this.selecProductResult[key].selectUnit.relationship;
			console.log('数量', this.selecProductResult[key].appForQuantity);

			console.log('key:', key, 'productId:', productId);

			// 筛选出产品ID匹配的库存项及其索引
			const inventProductsWithIndex = this.rawInventory
				.map((item, index) => ({ item, index }))
				.filter(({ item }) => {
					return (
						Array.isArray(item.productId) &&
						item.productId.some((p) => {
							const formatProductId = p._id + item.spec;
							return productId === formatProductId;
						})
					);
				});
             console.log('88888888',JSON.stringify(inventProductsWithIndex)  );
			// 根据type和key进一步筛选
			const filterData = inventProductsWithIndex.filter(({ item }) => item[type] === key);

			let remainingQuantity = this.selecProductResult[key].appForQuantity;
			console.log("请求数",remainingQuantity);
			if (remainingQuantity === 0) {
				return;
			}
             console.log('.......',filterData);
			// 遍历筛选后的数据，更新原始数组中的元素
			for (let i = 0; i < filterData.length; i++) {
				console.log('循环次数', i);
				const { item, index: originalIndex } = filterData[i];
				// 直接修改原始数组中的元素
				if (item.currentQuantity >= remainingQuantity) {
					//暂时不要改原始数量
					this.rawInventory[originalIndex].outQuantity = remainingQuantity;

					remainingQuantity = 0;
					break;
				} else {
					this.rawInventory[originalIndex].outQuantity = item.currentQuantity;
					remainingQuantity -= item.currentQuantity;
				}
			}

			// 处理库存不足的情况
			if (remainingQuantity > 0) {
				uni.showModal({
					title: '库存不足',
					content: `库存不足，剩余需出库数量：${remainingQuantity}`
				});
				console.warn('库存不足，剩余需出库数量：', remainingQuantity);
			}
		}
	}
};
</script>
<style lang="scss" scoped>
@import '@/common/variables.scss';
@import '@/common/global.scss';
.inventory-page {
	padding: 20rpx;
	background-color: $bg-secondary;
	min-height: 100vh;
	font-size: 28rpx;
	min-width: 70%;
	color: $text-primary;
}
.form_head {
	display: flex;
	position: relative;
	align-items: center;
	border-bottom: 2rpx solid #eee;
	margin-bottom: 30rpx;
	.info_item {
		display: flex;
		padding: 20rpx 30rpx;
		gap: 10rpx;
		border: 1rpx solid $border-color;
		border-radius: 10rpx; // 圆形搜索框
	}
	.form_code {
		position: absolute;
		bottom: 0;
		right: 0;
		font-size: 28rpx;
		color: #666;
	}
}
// 页面标题
.page-title {
	font-size: 36rpx;
	font-weight: 600;
	text-align: center;
	padding: 20rpx 0 30rpx;
	color: $text-primary;
	border-bottom: 1rpx solid $border-color;
	margin-bottom: 20rpx;
}

// 仓库/货主选择区
.select-section {
	display: flex;
	gap: 20rpx;
	margin-bottom: 24rpx;

	view {
		flex: 1;
		background-color: $bg-primary;
		padding: 20rpx;
		border-radius: $radius;
		box-shadow: $shadow;
		font-size: 28rpx;
		color: $text-secondary;
		cursor: pointer;
		transition: $transition;

		&:hover {
			background-color: $hover-color;
		}
	}
}

// 搜索栏
.search-bar {
	margin-bottom: 24rpx;

	.search-input {
		padding: 18rpx 20rpx 18rpx 60rpx; // 左侧留图标位置
		border: 1rpx solid $border-color;
		border-radius: 60rpx; // 圆形搜索框
		background-color: $bg-primary;
		font-size: 28rpx;
		position: relative;

		&::before {
			content: '🔍';
			position: absolute;
			left: 20rpx;
			top: 50%;
			transform: translateY(-50%);
			color: $text-tertiary;
		}

		&:focus {
			border-color: $primary-color;
			outline: none;
			box-shadow: 0 0 0 4rpx $primary-light;
		}
	}
}

// 显示模式切换
.display-mode {
	display: flex;
	align-items: center;
	gap: 16rpx;
	flex-wrap: wrap;
	padding: 0 4rpx;
	width: 50%;
	text {
		color: $text-secondary;
		white-space: nowrap;
	}

	.segmented-control {
		display: flex;
		flex: 1;
		height: 60rpx;
		background-color: $bg-primary;
		border-radius: 10rpx;
		border: 1rpx solid $border-color;
		overflow: hidden;
	}

	.segmented-item {
		flex: 1;
		text-align: center;
		line-height: 60rpx; // 垂直居中
		font-size: 26rpx;
		color: $text-secondary;
		transition: $transition;
		cursor: pointer;

		&.active {
			background-color: $primary-light;
			color: white;
			font-weight: 500;
		}

		&:not(.active):hover {
			background-color: $hover-color;
		}
	}
}

// 筛选面板
.filter-panel {
	background-color: $bg-primary;
	border-radius: $radius;
	box-shadow: $shadow;
	margin-bottom: 24rpx;
	overflow: hidden;

	.collapse {
		border: none;

		.collapse-header {
			display: flex;
			justify-content: space-between;
			align-items: center;
			padding: 20rpx 24rpx;
			background-color: $primary-light;
			cursor: pointer;

			text {
				font-size: 28rpx;
				color: $primary-color;
				font-weight: 500;
			}

			.arrow {
				color: $primary-color;
				transition: transform 0.3s ease;
			}

			.arrow.rotate {
				transform: rotate(180deg);
			}
		}
	}
	.collapse-content {
		padding: 0;

		overflow: hidden;
		transition: max-height 0.3s ease;

		&.expanded {
			max-height: 1000rpx; // 足够大的值实现展开动画
		}
	}

	.filter-group {
		padding: 24rpx;

		.filter-item {
			display: flex;
			align-items: center;
			margin-bottom: 24rpx;
			gap: 16rpx;
			flex-wrap: wrap;

			&:last-child {
				margin-bottom: 0;
			}

			.filter-label {
				width: 140rpx;
				flex-shrink: 0;
				font-size: 28rpx;
				color: $text-secondary;
			}

			.select-wrapper {
				flex: 1;
				min-width: 240rpx;
			}

			.select-control {
				width: 100%;
				padding: 16rpx;
				border: 1rpx solid $border-color;
				border-radius: $radius;
				font-size: 28rpx;
				background-color: $bg-primary;

				&:focus {
					border-color: $primary-color;
					outline: none;
				}
			}

			.date-input,
			.text-input {
				padding: 16rpx;
				border: 1rpx solid $border-color;
				border-radius: $radius;
				font-size: 28rpx;

				&:focus {
					border-color: $primary-color;
					outline: none;
				}
			}

			.date-input {
				width: 220rpx;
			}

			.text-input {
				flex: 1;
				min-width: 240rpx;
			}

			.range-separator {
				margin: 0 10rpx;
				color: $text-tertiary;
			}
		}

		.filter-actions {
			display: flex;
			justify-content: flex-end;
			gap: 16rpx;
			margin-top: 30rpx;
			padding-top: 20rpx;
			border-top: 1rpx solid $border-color;
		}

		.filter-stats {
			padding: 16rpx 0 0;
			font-size: 26rpx;
			color: $text-tertiary;
			text-align: right;
		}
	}
}

// 操作按钮区
.operation-buttons {
	display: flex;
	gap: 16rpx;
	margin-bottom: 24rpx;
	flex-wrap: wrap;

	.btn {
		padding: 16rpx 28rpx;
		border-radius: $radius;
		font-size: 28rpx;
		border: none;
		cursor: pointer;
		display: inline-flex;
		align-items: center;
		justify-content: center;
		transition: $transition;

		.icon {
			margin-right: 8rpx;
			font-size: 30rpx;
		}

		&:hover {
			opacity: 0.9;
			transform: translateY(-2rpx);
		}

		&:active {
			transform: translateY(0);
		}
	}

	.default-btn {
		background-color: $bg-primary;
		color: $text-secondary;
		border: 1rpx solid $border-color;
	}

	.primary-btn {
		background-color: $primary-color;
		color: white;

		&.plain {
			background-color: transparent;
			color: $primary-color;
			border: 1rpx solid $primary-color;
		}
	}
}



// 加载状态
.loading-state {
	display: flex;
	flex-direction: column;
	align-items: center;
	padding: 80rpx 0;

	.spinner {
		width: 50rpx;
		height: 50rpx;
		border: 5rpx solid $primary-light;
		border-top: 5rpx solid $primary-color;
		border-radius: 50%;
		animation: spin 1s linear infinite;
		margin-bottom: 20rpx;
	}

	text {
		color: $text-tertiary;
		font-size: 28rpx;
	}
}

@keyframes spin {
	0% {
		transform: rotate(0deg);
	}
	100% {
		transform: rotate(360deg);
	}
}

// 空状态
.empty-state {
	display: flex;
	flex-direction: column;
	align-items: center;
	padding: 80rpx 0;
	color: $text-tertiary;

	.empty-icon {
		font-size: 80rpx;
		margin-bottom: 24rpx;
		color: $border-color;
	}

	text {
		font-size: 28rpx;
	}
}

// 产品列表样式
.product-total {
	display: flex;
	flex-direction: column;
}


// 产品图片
.product_img {
	width: 80rpx; // 增大图片容器
	height: 80rpx;
	border-radius: $radius;
	overflow: hidden;
	margin: 0 auto;

	image {
		width: 100%;
		height: 100%;
		object-fit: cover;
	}
}

// 选中产品的详情区域



// 加载更多
.load-more {
	padding: 22rpx;
	text-align: center;
	color: $primary-color;
	font-size: 28rpx;
	border: 1rpx dashed $border-color;
	border-radius: $radius;
	margin: 24rpx 0;
	cursor: pointer;
	transition: $transition;
	background-color: $bg-primary;

	&:hover {
		background-color: $primary-light;
	}

	text {
		display: inline-flex;
		align-items: center;
	}

	text::before {
		content: '↓';
		margin-right: 8rpx;
	}
}

// 商品名称和ID样式
// 表格文本样式优化




</style>
